/*******************************************************************************
 * Copyright 2020 huanggefan.cn
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ******************************************************************************/

package tools

import (
	"bytes"
	"crypto/md5"
	"crypto/sha1"
	"encoding/hex"
	"gitee.com/WisdomClassroom/core"
	"gitee.com/WisdomClassroom/resource/global"
	"hash"
	"io/ioutil"
	"net/http"
)

const MaxUploadSize = int64(1024 * 1024 * 100)

func GetFileMD5Prefix(data []byte, fileName string, userUUID string) string {
	var sum hash.Hash = md5.New()
	var buffer bytes.Buffer
	buffer.Write(data)
	buffer.WriteString(fileName)
	buffer.WriteString(userUUID)
	sum.Write(buffer.Bytes())
	c := hex.EncodeToString(sum.Sum(nil))
	return string(c[0:3])
}

func GetFileSHA(data []byte) string {
	var sum hash.Hash = sha1.New()
	sum.Write(data)
	c := hex.EncodeToString(sum.Sum(nil))
	return c
}

func ParseForm(resp http.ResponseWriter, req *http.Request) bool {
	req.Body = http.MaxBytesReader(resp, req.Body, MaxUploadSize)

	if err := req.ParseMultipartForm(MaxUploadSize); err != nil {
		return false
	} else {
		return true
	}
}

func GetFileOfForm(req *http.Request) (string, []byte, error) {
	name := req.PostFormValue(global.POSTFormFileName)
	file, _, err := req.FormFile(global.POSTFormFile)
	if err != nil {
		return "", []byte{}, err
	}

	fileBytes, err := ioutil.ReadAll(file)
	if err != nil {
		return "", []byte{}, err
	}

	_ = file.Close()

	return name, fileBytes, nil
}

func GetTokenInfoFromCookies(req *http.Request) (*core.Token, error) {
	cookie, err := req.Cookie(global.CookiesToken)
	if err != nil {
		return nil, err
	}

	token := core.NewToken()
	err = token.UnpackToken(cookie.Value, global.TokenCert)
	if err != nil {
		return nil, err
	}

	return token, nil
}

func GetFileUUIDFromURL(req *http.Request) (string, bool) {
	vars := req.URL.Query()
	if len(vars[global.QueryFileUUID]) == 0 {
		return "", false
	}

	return vars[global.QueryFileUUID][0], true
}

func GetChapterUUIDFromURL(req *http.Request) (string, bool) {
	vars := req.URL.Query()
	if len(vars[global.QueryChapterUUID]) == 0 {
		return "", false
	}

	return vars[global.QueryChapterUUID][0], true
}
